package com.ams.handler.baiy;

import com.alibaba.fastjson.JSONObject;
import com.ams.common.entity.RackMisItem;
import com.ams.common.entity.RackQtyItem;
import com.ams.common.utils.RedisKeys;
import com.ams.common.utils.RedisUtils;
import com.ams.common.utils.SnConstant;
import com.ams.enums.EntranceStatus;
import com.ams.enums.LightOperationStatus;
import com.ams.model.*;
import com.ams.service.*;
import com.ams.service.impl.WcsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class PalQtyHandler implements IBaiyHandler {

    @Autowired
    EntrancePrivilegeService entrancePrivilegeService;

    @Autowired
    DocAsnDetailsService docAsnDetailsService;

    @Autowired
    DocOrderDetailsService docOrderDetailsService;

    @Autowired
    BasLocationService basLocationService;

    @Autowired
    InvLotLocIdService invLotLocIdService;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    WcsService wcsService;

    @Override
    public boolean handle(List<Object> dataArr) {
        log.info("【PalQtyHandler handle】start >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        EntrancePrivilege entrancePrivilegeQuery = new EntrancePrivilege();
        entrancePrivilegeQuery.setEntrancestatus(EntranceStatus.ENTER.getMessage());
        EntrancePrivilege entrancePrivilege = entrancePrivilegeService.findFirstByModel(entrancePrivilegeQuery);
        if (entrancePrivilege == null) {
            return false;
        }
        log.info("【PalQtyHandler handle】EntrancePrivilege enter >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

        String orderno = entrancePrivilege.getOrderno();
        String rackId = (String)dataArr.get(1);
        String locationId = (String)dataArr.get(2);
        Integer qty = (Integer)dataArr.get(3);

        log.info("【PalQtyHandler handle】orderno = {} rackId = {} locationId = {} qty ={}>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", orderno, rackId, locationId, qty);
        String preQtyMsgStr = redisUtils.hget(RedisKeys.PRE_QTY_MSG, rackId + ":" + locationId);
        if(!StringUtils.isBlank(preQtyMsgStr)) {
            log.info("【PalQtyHandler handle】PRE_QTY_MSG find >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            String preMisMsgStr = redisUtils.hget(RedisKeys.RACK_MIS_LIST, rackId + ":" + locationId);
            if(!StringUtils.isBlank(preMisMsgStr)) {
                log.info("【PalQtyHandler handle】RACK_MIS_LIST find >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                RackMisItem rackMisItem = JSONObject.parseObject(preMisMsgStr, RackMisItem.class);
                Integer expectValue = rackMisItem.getExpectValue();
                RackQtyItem lastQtyData = JSONObject.parseObject(preQtyMsgStr, RackQtyItem.class);
                Integer offset = qty - lastQtyData.getQty();
                if (expectValue - offset == 0) {
                    log.info("【PalQtyHandler handle】RACK_MIS_LIST 清除 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    // 错误消失
                     redisUtils.hdel(RedisKeys.RACK_MIS_LIST, rackId + ":" + locationId);
                    if (redisUtils.hsize(RedisKeys.RACK_MIS_LIST) == 0) {
                        log.info("【PalQtyHandler handle 复位灯>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        // 复位灯
                        try {
                            wcsService.lightOperation(LightOperationStatus.NORMAL);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    log.info("【PalQtyHandler RACK_MIS_LIST expectValue = {} nowQty = {} lastQtyData = {}>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", expectValue, qty, lastQtyData);
                }
            }
        }

        RackQtyItem rackQtyItem = new RackQtyItem();
        rackQtyItem.setLocationId(locationId);
        rackQtyItem.setRackId(rackId);
        rackQtyItem.setQty(qty);
        String preQtyJson = JSONObject.toJSONString(rackQtyItem);
        redisUtils.hset(RedisKeys.PRE_QTY_MSG, rackId + ":" + locationId, preQtyJson);
        log.info("【PalQtyHandler】 PRE_QTY_MSG add >>>>>>>>>>>>>>>>");

        if (!checkMatInOrder(orderno, rackId, locationId)) {
            return false;
        }

        //todo 代码冗余了
        if (orderno.indexOf(SnConstant.DOC_ASN_PREFIX) > -1) {
            log.info("【PalQtyHandler】入库 >>>>>>>>>>>>>>>>");
            BasLocation basLocationQuery = new BasLocation();
            basLocationQuery.setLocationid(locationId);
            basLocationQuery.setRackId(rackId);
            BasLocation basLocation = basLocationService.findFirstByModel(basLocationQuery);
            if (basLocation != null) {
                DocAsnDetails docAsnDetailsQuery = new DocAsnDetails();
                docAsnDetailsQuery.setAsnno(orderno);
                docAsnDetailsQuery.setSku(basLocation.getSku());
                DocAsnDetails docAsnDetails = docAsnDetailsService.findFirstByModel(docAsnDetailsQuery);
                if (docAsnDetails != null) {
                    BigDecimal curStock = invLotLocIdService.getStockByLotId(rackId, locationId);
                    BigDecimal offsetStock = BigDecimal.valueOf(qty).subtract(curStock);
                    if(offsetStock.compareTo(BigDecimal.ZERO) > 0) {
                        docAsnDetails.setReceivedqty(offsetStock);
                        docAsnDetailsService.update(docAsnDetails);
                    }

                }
            }
        }else if(orderno.indexOf(SnConstant.DOC_ORDER_PREFIX) > -1){
            log.info("【PalQtyHandler】出库 >>>>>>>>>>>>>>>>");
            BasLocation basLocationQuery = new BasLocation();
            basLocationQuery.setLocationid(locationId);
            basLocationQuery.setRackId(rackId);
            BasLocation basLocation = basLocationService.findFirstByModel(basLocationQuery);
            if (basLocation != null) {
                DocOrderDetails docOrderDetailsQuery = new DocOrderDetails();
                docOrderDetailsQuery.setOrderno(orderno);
                docOrderDetailsQuery.setSku(basLocation.getSku());
                DocOrderDetails docOrderDetails = docOrderDetailsService.findFirstByModel(docOrderDetailsQuery);
                if (docOrderDetails != null) {
                    BigDecimal curStock = invLotLocIdService.getStockByLotId(rackId, locationId);
                    BigDecimal offsetStock = curStock.subtract(BigDecimal.valueOf(qty));
                    docOrderDetails.setQtyshipped(offsetStock);
                    if(offsetStock.compareTo(BigDecimal.ZERO) > 0) {
                        docOrderDetails.setQtyshipped(offsetStock);
                        docOrderDetailsService.update(docOrderDetails);
                    }
                }
            }
        }else {
            return false;
        }

        return true;
    }


    private boolean checkMatInOrder(String orderno, String rackId, String locationId) {
        BasLocation basLocationQuery = new BasLocation();
        basLocationQuery.setLocationid(locationId);
        basLocationQuery.setRackId(rackId);
        BasLocation basLocation = basLocationService.findFirstByModel(basLocationQuery);
        if (basLocation == null) {
            return false;
        }

        if (orderno.indexOf(SnConstant.DOC_ASN_PREFIX) > -1) {
            DocAsnDetails docAsnDetailsQuery = new DocAsnDetails();
            docAsnDetailsQuery.setAsnno(orderno);
            docAsnDetailsQuery.setSku(basLocation.getSku());
            DocAsnDetails docAsnDetails = docAsnDetailsService.findFirstByModel(docAsnDetailsQuery);
            if (docAsnDetails != null) {
                return true;
            }
        }else if(orderno.indexOf(SnConstant.DOC_ORDER_PREFIX) > -1){
            DocOrderDetails docOrderDetailsQuery = new DocOrderDetails();
            docOrderDetailsQuery.setOrderno(orderno);
            docOrderDetailsQuery.setSku(basLocation.getSku());
            DocOrderDetails docOrderDetails = docOrderDetailsService.findFirstByModel(docOrderDetailsQuery);
            if (docOrderDetails != null) {
                return true;
            }
        }
        return false;
    }
}
